package org.jeecg.modules.friends.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.modules.friends.condition.VipUserCondition;
import org.jeecg.modules.friends.dao.VipUserDAO;
import org.jeecg.modules.friends.mapper.ext.VipUserDOExtMapper;
import org.jeecg.modules.friends.model.VipUserDO;
import org.jeecg.modules.friends.user.entity.User;
import org.jeecg.modules.friends.user.param.OperateAuthInfoParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Iterables;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class VipUserServiceImpl implements org.jeecg.modules.friends.service.VipUserService {
    @Autowired
    private VipUserDAO vipUserDAO;
    @Autowired
    private VipUserDOExtMapper vipUserDOExtMapper;

    public VipUserDO findByUserId(Long userId) {
        return vipUserDAO.findByUserId(userId);
    }

    @Override
    public void addVipUser(User user, int vipLevel, int tickLeft, Long vipExpireTime) {
        VipUserDO vipUserDO = findByUserId(user.getId());
        if (Objects.isNull(vipUserDO)) {
            vipUserDO = new VipUserDO();
            vipUserDO.setUserId(user.getId());
            vipUserDO.setAddTime(new Date());
            vipUserDO.setVipLevel(vipLevel);
            vipUserDO.setUpdateTime(new Date());
            vipUserDO.setTicketLeft(tickLeft);
            vipUserDO.setVipStartDate(System.currentTimeMillis());
            vipUserDO.setVipEndDate(System.currentTimeMillis() + vipExpireTime);
            vipUserDAO.insert(vipUserDO);
            return;
        }
        if (vipUserDO.getVipEndDate() > System.currentTimeMillis()) {
            vipUserDO.setVipEndDate(vipUserDO.getVipEndDate() + vipExpireTime);
            //会员没过期
        } else {
            vipUserDO.setVipEndDate(System.currentTimeMillis() + vipExpireTime);
            vipUserDO.setTicketLeft(tickLeft);
        }
        vipUserDO.setUpdateTime(new Date());
        vipUserDAO.update(vipUserDO);
    }

    @Override
    public void deleteByUserId(Long userId) {
        vipUserDAO.deleteByUserId(userId);
    }

    @Override
    public void minusVipUser(User user, int level, int ticket, long l) {
        VipUserDO vipUserDO = findByUserId(user.getId());
        if (vipUserDO == null) {
            return;
        }
        int count = vipUserDO.getTicketLeft() - ticket;
        vipUserDO.setTicketLeft(count > 0 ? count : 0);
        vipUserDO.setVipEndDate(vipUserDO.getVipEndDate() - l);
        vipUserDAO.update(vipUserDO);
    }


    @Override
    public void operateAuthInfo(OperateAuthInfoParam param) {
        log.info("开始发券.....");
        long current = System.currentTimeMillis();
        long countVip = vipUserDAO.countVipUser(current);
        if (countVip > 0) {
            int page = (int) (countVip / 100 + 1);
            int pageSize = 3000;
            for (int i = 0; i < page; i++) {
                List<VipUserDO> vipUserDOS = vipUserDAO.findVipUserByPage(i * pageSize, pageSize, current);
                if (CollectionUtils.isNotEmpty(vipUserDOS)) {
                    List<Long> vipIds = vipUserDOS.stream().map(VipUserDO::getId).collect(Collectors.toList());
                    vipUserDAO.updateTicketLeftByIds(vipIds);
                }
            }
        }
        log.info("结束发券.....");

    }

    @Override
    public void sendTicket() {
        long leftId = 0;
        while (true) {
            VipUserCondition vipCondition = new VipUserCondition();
            vipCondition.createCriteria()
                    .andIdGreaterThan(leftId);
            vipCondition.setOrderByClause("id asc");
            vipCondition.setLimit(1000);
            List<VipUserDO> vipUsers = vipUserDOExtMapper.selectByCondition(vipCondition);

            if (CollectionUtil.isEmpty(vipUsers)) {
                break;
            }
            VipUserDO last = Iterables.getLast(vipUsers);
            leftId = last.getId() + 1;
            List<Long> vipIds = vipUsers.stream()
                    .filter((x) -> x.getVipEndDate() >= System.currentTimeMillis())
                    .map(VipUserDO::getId).collect(Collectors.toList());
            vipUserDAO.updateTicketLeftByIds(vipIds);
            log.info("sendTicket 最后一个元素ID：" + last.getId());
        }
    }
}
